package com.crayon.account.service;

import android.content.Context;

import com.crayon.account.dao.DAOAccount;
import com.crayon.account.dao.DataBaseManager;
import com.crayon.account.data.EDAType;
import com.crayon.util.GDB;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 메세지에서 카드사와 가격 사용처 시간을 가져와 입력해준다. 
 * @author kws
 *
 */
public class SMSService {
	
	String message;
	Date stamp;
	long price;
	String place;
	String cardName;
	public SMSService(){
		
	}
	
	public SMSService(String message,Date stamp){
		this.message = message;
		this.stamp = stamp;
		
		for(SMSFilters filter: SMSFilters.values()){
			for(String name : filter.smscards.mCards){
				if(message.startsWith(name)){
					cardName = name;
//					GDB.log(getClass(), "FIND 필더" + name);
					processPrice(filter, StringUtils.substring(message,StringUtils.indexOfAny(message, name)));
					processFindPlace(filter,StringUtils.substring(message,StringUtils.indexOfAny(message, name)));
					break;
				}
			}
		}
	}
	private void processPrice(SMSFilters filter,String message){
//		for(String parse : filter.smsPrice.mFilter){
		List<Long> prices = getPrice(filter.smsPrice.mFilter	, message);
		for(long p : prices){
//			GDB.log(getClass(), " price " + p);
			price = p;
		}
		
		
//		}
	}
	private String processFindPlace(SMSFilters filter,String message){
		char[] chars = {'\t','\\',':','/','*','-'};
		String[] endStr = {"원","님","카드","누적","일시","승인","취소"};
		String[] conStr = {"일시불","누계","누적","개월","일시"};
	
		//원자로 끝나는 문자열을 제외시킨다.
		for(String name : filter.smscards.mCards)
		StringUtils.remove(message, name);
		StringUtils.remove(message, "일시불");
		try {
			String[] array = message.split(" ");
			GDB.log(getClass(), "array size " + array.length);
			List<String> list = Arrays.asList(array);
			List<String> list2=new ArrayList<String>();
			for(String item : list){
				if(StringUtils.endsWithAny(item, endStr) 
				|| StringUtils.containsAny(item, chars)){
				
//					list.remove(item);
				}else{
					boolean contain=false;
					for(String con : conStr){
						contain = item.contains(con);
						if(contain) break;
					}
					if(item.length()>0 && contain==false)
					list2.add(item);
				}
//			}else if(StringUtils.containsAny(item, chars)){
//				list.remove(item);
//			}

			}
			for(String item : list2){
				GDB.log(getClass(), "\titem["+item.length()+"]" + item);
			}
			
			if(list2!=null && list2.size()>0){
				place = Arrays.toString(list2.toArray());
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}
//		List<String> list = new ArrayList<String>();
//		for(String a: array)list.add(a);
//		for(String item : list){
//			if(StringUtils.endsWithAny(item, outstr)){
//				list.remove(item);
//			}else if(StringUtils.containsAny(item, chars)){
//				list.remove(item);
//			}
//		}
//		//원자로된 것을 다지운다.
//		GDB.log(getClass(), "list.size " + list.size());
		
		return null;
	}
	private List<Long> getPrice(String[] formalStringMoney ,String data){
		ArrayList<Long> prices=new ArrayList<Long>();
		if(data!=null) data  = StringUtils.trim(data);
		for (int k = 0; k < formalStringMoney.length; k++) {
//			GDB.log(getClass(), " formalStringMoney["+k+"] " + formalStringMoney[k]);
			Pattern p = Pattern.compile(formalStringMoney[k]);
			for (int i = 0; i < data.length() - 1; i++) {
				String temp = data.substring(i, data.length());
				Matcher m = p.matcher(temp.trim());
				if (m.matches()) {
					// 상세 내역 뽑아 내기
					if(temp.contains("원")){
						temp = temp.substring(0, temp.indexOf("원"));
					}
					if(temp!=null && temp.length() <10){
						try {
							temp = StringUtils.remove(temp, ",");
							long price = Long.parseLong(temp);
//							GDB.log(getClass(), "retMoney sms price = " + price +"\t ["+k+"]format " + formalStringMoney[k]  + "\t msg" +data );
							prices.add(price);
							return prices;
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				}
			}
		}
		return prices;
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
//		return super.toString();
		return String.format("카드 [%s]\t장소 [%s]\t 가격 :%d\tmsg=%s", cardName,place,price,message);
	}
	

	public void saveDaoDB(Context context){
		if(getCardName()!=null){
			DataBaseManager baseManager = DataBaseManager.getHelper(context);
			try {
				DAOAccount daoAccount =new DAOAccount(EDAType.OUTCOM);
				daoAccount.setSummary(getPlace());
				
				daoAccount.setXaccountName(getCardName());
				daoAccount.setXprice(getPrice());
				daoAccount.setDtStart(getStamp());
				daoAccount.setDtSyncKey(getStamp());
				daoAccount.setDesciption(getMessage());
				baseManager.getDAOAccount().createIfNotExists(daoAccount);
				
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public Date getStamp() {
		return stamp;
	}

	public void setStamp(Date stamp) {
		this.stamp = stamp;
	}

	public long getPrice() {
		return price;
	}

	public void setPrice(long price) {
		this.price = price;
	}

	public String getPlace() {
		return place;
	}

	public void setPlace(String place) {
		this.place = place;
	}

	public String getCardName() {
		return cardName;
	}

	public void setCardName(String cardName) {
		this.cardName = cardName;
	}
}
